<script setup lang="ts">
import { ref, h, reactive, onMounted } from 'vue'
import { NForm, NSpace, NFormItem, NInput, NDatePicker, NTag, NButton, NDataTable, NPagination, useNotification, useDialog } from 'naive-ui'
import type { DataTableRowKey, DataTableColumns } from 'naive-ui'
import { useDictStore } from '@/stores/dictStore'
import { useUserStore } from '@/stores/userStore'
import http from '@/tools/http'

const notification = useNotification()
const dialog = useDialog()
const dictStore = useDictStore()
const userStore = useUserStore()

type RowData = {
    logId?: string
    userId?: string
    ip?: string
    address?: string
    browserInfo?: string
    operatingSystemInfo?: string
    loginStatus?: string
    loginTime?: string
}

type SearchFromType = {
    pageNum: number,
    pageSize: number,
    userId?: string,
    ip?: string,
    loginTimeRange: [string, string] | null
}

const userLoginLogTableColumns: DataTableColumns = [
    {
        type: 'selection',
        width: 25
    }, {
        title: "用户ID(账号)",
        key: "userId",
        width: 70,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "IP地址",
        key: "ip",
        width: 80,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "登录地点",
        key: "address",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "浏览器",
        key: "browserInfo",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "操作系统",
        key: "operatingSystemInfo",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "登录状态",
        key: "loginStatus",
        width: 100,
        render(rowData: RowData, rowIndex: number) {
            return h(
                NTag,
                {
                    type: rowData.loginStatus === '0' ? 'success' : 'error'
                },
                () => dictStore.dictItem("LOGIN_STATUS", rowData.loginStatus)
            )
        }
    }, {
        title: "登录日期",
        key: "loginTime",
        width: 120
    }
]

const userLoginLogData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const userLoginLogSearchFormValue = reactive<SearchFromType>({
    pageNum: 1,
    pageSize: 10,
    userId: "",
    ip: "",
    loginTimeRange: null
})

const checkedRowKeys = ref<DataTableRowKey[]>([])

onMounted(() => {
    pageUserLoginLog()
})

function handleCheckRowKeys(rowKeys: DataTableRowKey[]) {
    checkedRowKeys.value = rowKeys
}

function pageNumChange(pageNum: number) {
    userLoginLogSearchFormValue.pageNum = pageNum
    pageUserLoginLog()
}

function pageSizeChange(pageSize: number) {
    userLoginLogSearchFormValue.pageSize = pageSize
    pageUserLoginLog()
}

function pageUserLoginLog() {
    let start = ""
    let end = ""
    if (userLoginLogSearchFormValue.loginTimeRange) {
        start = userLoginLogSearchFormValue.loginTimeRange[0]
        end = userLoginLogSearchFormValue.loginTimeRange[1]
    }
    const request = {
        pageNum: userLoginLogSearchFormValue.pageNum,
        pageSize: userLoginLogSearchFormValue.pageSize,
        userId: userLoginLogSearchFormValue.userId,
        ip: userLoginLogSearchFormValue.ip,
        loginTimeStart: start,
        loginTimeEnd: end
    }
    http.post("/system/log/login/page", request).then(({ data }) => {
        if (data.code === "0") {
            userLoginLogData.pageNum = data.data.pageNum
            userLoginLogData.pageSize = data.data.pageSize
            userLoginLogData.pages = data.data.pages
            userLoginLogData.total = data.data.total
            userLoginLogData.list.length = 0
            for (let i = 0; i < data.data.list.length; i++) {
                userLoginLogData.list.push(data.data.list[i])
            }
        }
    })
}

function batchDeleteLog() {
    dialog.create({
        title: '温馨提示',
        content: '确定删除选中的日志吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            http.post("/system/log/login/batch-delete", checkedRowKeys.value).then(({ data }) => {
                if (data.code === "0") {
                    notification['success']({
                        content: '删除成功',
                        meta: `${data.msg}`,
                        duration: 2500,
                        keepAliveOnHover: true
                    })
                    pageUserLoginLog()
                }
            })
        }
    })
}
function clearLog() {
    dialog.create({
        title: '温馨提示',
        content: '确定清空所有日志吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            http.post("/system/log/login/clear").then(({ data }) => {
                if (data.code === "0") {
                    notification['success']({
                        content: '清空成功',
                        meta: `${data.msg}`,
                        duration: 2500,
                        keepAliveOnHover: true
                    })
                    pageUserLoginLog()
                }
            })
        }
    })
}
</script>

<template>
    <div id="flame-container">
        <div class="search">
            <n-form :model="userLoginLogSearchFormValue" inline label-placement="left">
                <n-form-item label="用户ID(账号)">
                    <n-input v-model:value="userLoginLogSearchFormValue.userId" placeholder="请输入用户ID(账号)" clearable />
                </n-form-item>
                <n-form-item label="IP地址">
                    <n-input v-model:value="userLoginLogSearchFormValue.ip" placeholder="请输入IP地址" clearable />
                </n-form-item>
                <n-form-item label="登录日期">
                    <n-date-picker v-model:formatted-value="userLoginLogSearchFormValue.loginTimeRange" type="daterange"
                        placeholder="请选择日期范围" clearable />
                </n-form-item>
                <n-form-item>
                    <n-button attr-type="button" @click="pageUserLoginLog()">查询</n-button>
                </n-form-item>
            </n-form>
        </div>
        <div class="btn-group">
            <n-space>
                <n-button v-if="userStore.hasAuth('login-log:batch-delete')" :disabled="checkedRowKeys.length === 0"
                    attr-type="button" @click="batchDeleteLog()">批量删除</n-button>
                <n-button v-if="userStore.hasAuth('login-log:clear')" attr-type="button"
                    @click="clearLog()">清空所有日志</n-button>
            </n-space>
        </div>
        <div class="data-table">
            <n-data-table :scroll-x="705" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
                :row-key="row => row.logId" @update:checked-row-keys="handleCheckRowKeys"
                :columns="userLoginLogTableColumns" :data="userLoginLogData.list" :bordered="false" />
        </div>
        <div class="pagination">
            <n-pagination style="float:right" v-model:page="userLoginLogData.pageNum" :page-size="userLoginLogData.pageSize"
                :item-count="userLoginLogData.total" :page-sizes="[5, 10, 30, 50, 100]" :on-update-page="pageNumChange"
                :on-update-page-size="pageSizeChange" show-quick-jumper show-size-picker />
        </div>
    </div>
</template>

<style scoped>
.display-flex-end {
    display: flex;
    width: 100%;
    justify-content: flex-end;
}
</style>